package cn.yl.fxboot.application.action;

import java.io.File;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import cn.yl.fxboot.application.action.handler.WebViewHandler;
import cn.yl.fxboot.application.action.model.AuthorStartActModel;
import cn.yl.fxboot.application.common.utils.SpringUtils;
import cn.yl.fxboot.application.service.Common;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.MapChangeListener;
import javafx.collections.ObservableMap;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.scene.web.WebView;
import javafx.stage.DirectoryChooser;

public class AuthorActions {
	
	public EventHandler<ActionEvent> authorAddrBtnHandler(TextField node) {
		return new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				DirectoryChooser dirChooser = new DirectoryChooser();
				dirChooser.setTitle("选择导出文件夹");
				File dir = dirChooser.showDialog(node.getScene().getWindow());
				if (dir != null) {
					node.setText(dir.getPath());
				}
			}
		};
	}
	public EventHandler<ActionEvent> authorDownHandler(AuthorStartActModel model) {
		TextField authorAddr_TF = model.getAuthorAddrTF();
		TextArea authorUrl_TA = model.getAuthorUrlTA();
		WebView authorView_WV = model.getAuthorViewWV();
		
		return new EventHandler<ActionEvent>() {
			String taskId ;
			@Override
			public void handle(ActionEvent event) {
				taskId = "任务 " + RandomUtil.randomString(4) + " --> ";
				Task<Void> task = new Task<Void>() {
					@Override
					protected void running() {
						updateMessage("开始!");
					}

					@Override
					protected void cancelled() {
						updateMessage("error:被中断!");
					}

					@Override
					protected void failed() {
						updateMessage("error:失败!");
					}
					@Override
					protected void succeeded() {}
					@Override
					protected Void call() throws Exception {
						String urls = authorUrl_TA.getText();
						List<String> urlList = ReUtil.findAllGroup0(Common.RE_URLS, urls);
						updateMessage("解析到" + urlList.size() + "条作者連接,正在準備下載...");
						ConcurrentHashMap<String,Object> countMap = new ConcurrentHashMap<String,Object>();
						countMap.put("count", 0);
						countMap.put("totalUrl", 0L);
						countMap.put("total", 0L);
						final ObservableMap<String, Object> obMap = FXCollections.synchronizedObservableMap(FXCollections.observableMap(countMap));
						obMap.addListener(new MapChangeListener<String, Object>(){
							@Override
							public void onChanged(Change<? extends String, ? extends Object> change) {
								long total = (Long)change.getMap().get("total");
								long totalUrl = (Long)change.getMap().get("totalUrl");
								Object c = change.getValueAdded();
								if(change.wasAdded()) {
									if(c instanceof Integer) {
										if((Integer)c == 0 ) {
											long cur = totalUrl + 1L;
											countMap.put("totalUrl", cur);
											if(cur == urlList.size()) {
												Platform.runLater(()->{
													MsgPaneActions.doLog("success:任务"+taskId+"-->所有下载("+total+")已完成");
													Pane authorPane = (Pane) authorAddr_TF.getScene().lookup("#mainPane");
													authorPane.getChildren().forEach(n ->{
														if(n instanceof WebView) {
															n = null;
														}
													});
												});
											}
											Platform.runLater(()->{
												MsgPaneActions.doLog("success:任务"+taskId+"-->所有下载("+total+")已完成");
												Pane authorPane = (Pane) authorAddr_TF.getScene().lookup("#mainPane");
												authorPane.getChildren().forEach(n ->{
													if(n instanceof WebView) {
														n = null;
													}
												});
											});
										}
									}
								}
							}
							
						});
						
						for (int i = 0; i < urlList.size(); i++) {
							String curUrl = urlList.get(i);
							Platform.runLater(() ->{
								WebView wv = WebViewHandler.initWebView(new WebView(), authorAddr_TF,  taskId,  obMap);
								wv.setVisible(false);
								Pane authorPane = (Pane) authorView_WV.getScene().lookup("#mainPane");
								authorPane.getChildren().add(wv);
								wv.getEngine().load(curUrl);
							});
						}
						return null;
					}

				};
				task.messageProperty().addListener(new ChangeListener<String>() {
					@Override
					public void changed(ObservableValue<? extends String> observable, String oldValue,
							String newValue) {
						MsgPaneActions.doLog(taskId + newValue);
					}
				});
				Executor pool =  (Executor) SpringUtils.getBean("customServiceExecutor"); 
				pool.execute(task);
			}
		};
	}
	public EventHandler<ActionEvent> clearBtnHandler(Button clear_Btn) {
		return new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				Pane authorPane = (Pane) clear_Btn.getScene().lookup("#mainPane");
				authorPane.getChildren().forEach(n ->{
					if(n instanceof WebView) {
						n = null;
					}
				});
				MsgPaneActions.clean();
			}
			
		};
	}

}
